package com.xrtn.controller;

import com.xrtn.bean.SysUserInfo;
import com.xrtn.bean.TBackcardInfo;
import com.xrtn.bean.TPatientInfo;
import com.xrtn.bean.TUserInfo;
import com.xrtn.page.Page;
import com.xrtn.service.ICommonService;
import com.xrtn.service.ISysUserService;
import com.xrtn.service.IUserService;
import com.xrtn.utils.CodeEnum;
import com.xrtn.utils.HttpUtils;
import com.xrtn.utils.ObjUtils;
import com.xrtn.utils.ResponseData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.apache.http.protocol.HTTP;
import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by tu_pei on 2018/3/5.
 */
@Api("用户相关接口")
@Controller
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/user")
public class UserController {

    @Autowired
    private ICommonService commonService;

    @Autowired
    private IUserService userService;
    /**
     * 进入会员管理页面
     * @return
     */
    @RequestMapping(value = "/gotoVip",method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView gotoVip(ModelAndView modelAndView){
        modelAndView.setViewName("vip");
        return modelAndView;
    }
    /**
     * 进入添加会员页面
     * @return
     */
    @RequestMapping(value = "/gotoAddVip",method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView gotoAddVip(ModelAndView modelAndView){
        modelAndView.setViewName("vipAdd");
        return modelAndView;
    }
    /**
     * 进入会员详情页面
     * @return
     */
    @RequestMapping(value = "/gotoVipDetail",method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView gotoVipDetail(ModelAndView modelAndView){
        modelAndView.setViewName("vipUserDetail");
        return modelAndView;
    }
    /**
     * 进入会员充值页面
     * @return
     */
    @RequestMapping(value = "/gotoHomeRecharge",method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView gotoHomeRecharge(ModelAndView modelAndView){
        modelAndView.setViewName("home/home-recharge");
        return modelAndView;
    }
    /**
     * 进入会员对账（扣款）页面
     * @return
     */
    @RequestMapping(value = "/gotoHomeDeduction",method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView gotoHomeDeduction(ModelAndView modelAndView){
        modelAndView.setViewName("home/home-deduction");
        return modelAndView;
    }
    /**
     * 根据用户信息查询用户
     * @return
     */
    @ApiOperation(value = "查询用户列表",notes="查询用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userPhone",dataType="string",required=false,value="手机号",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="timeType",dataType="int",required=false,value="时间分类：0，1，2，3，4：全部，一，二，三，超过三个月未到店",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="payCount",dataType="int",required=false,value="就诊开始次数",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="payCounts",dataType="int",required=false,value="就诊结束次数",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="levelType",dataType="int",required=false,value="会员等级：0，1，2，3，4，：全部，普通，白银，黄金，铂金会员",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userFrom",dataType="string",required=false,value="来源：0，1，2，3 ：全部，线下，线上，外部，",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="subclinicId",dataType="string",required=false,value="分店id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="numberStart",dataType="int",required=false,value="下限就诊次数",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="numberEnd",dataType="int",required=false,value="上限就诊次数",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="rechargeFrom",dataType="int",required=false,value="充值金额开始",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="rechargeTo",dataType="int",required=false,value="充值金额结束",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="page",dataType="string",required=false,value="当前页数",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="limit",dataType="string",required=false,value="显示多少条记录",defaultValue = "10"),
            @ApiImplicitParam(paramType="query",name="fromPage",dataType="string",required=false,value="从那个页面查询，0：会员中心",defaultValue = "0"),
    })
    @RequestMapping(value = "/selectUserList",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectUserList(HttpServletRequest request, String userPhone, Integer timeType,
                                       Integer payCount, Integer payCounts, Integer levelType, String userFrom, Integer rechargeFrom, Integer rechargeTo,
                                       Integer subclinicId,Integer page, Integer limit,Integer numberStart,Integer numberEnd, String fromPage){

        ResponseData data = new ResponseData();

        Map<String,Object> params = new HashMap<>();
        params.put("userPhone", userPhone);
        params.put("timeType", timeType);
        params.put("payCount", payCount);
        params.put("payCounts", payCounts);
        params.put("levelType", levelType);
        params.put("userFrom", userFrom);
        params.put("subclinicId", subclinicId);
        params.put("numberStart",numberStart);
        params.put("numberEnd",numberEnd);
        params.put("rechargeFrom",rechargeFrom);
        params.put("rechargeTo",rechargeTo);
        params.put("fromPage",fromPage);

//        if(ObjUtils.isEmpty(numberEnd) && ObjUtils.isEmpty(numberStart)){
//            params.put("numberStart",null);
//            params.put("numberEnd",null);
//        }else{
//
//            if(numberEnd > 1){
//                params.put("numberEnd",numberEnd);
//            }
//            if(numberEnd == 1 && numberStart == 1){
//                params.put("numberStart",null);
//                params.put("numberEnd",null);
//            }
//        }

        if ("0".equals(fromPage)) { // 从会员中心查询
            SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(HttpUtils.CURRENT_USER_4_POJO);
            params.put("loginUser",userInfo);
        }

        page = page == null ? 1 : page;
        limit = limit == null ? Integer.MAX_VALUE : limit;
        Page pages = Page.newBuilder(page, limit);

        Page userList = userService.selectUserPageList(pages,params);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("rows", userList.getItems());
        map.put("records", userList.getTotalRecord());
        map.put("total", userList.getTotalPage());
        map.put("page", userList.getPageNo());
        data.setResults(map);

        // 返回数据
        return data;
    }

    /**
     * @Title: exportPatientList
     * @Description: 导出患者列表
     * @param @return
     * @return ResponseData
     * @throws
     */
    @ApiOperation(value = "导出患者列表",notes="导出患者列表")
    @RequestMapping(value = "/exportUserList",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData exportUserList(HttpServletRequest request,HttpServletResponse response){
        userService.exportUserList(request,response);
        return null;
    }


    /**
     * 根据用户信息查询用户
     * @return
     */
    @ApiOperation(value = "查询用户详情",notes="查询用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userId",dataType="int",required=false,value="用户id",defaultValue = "1"),
    })
    @RequestMapping(value = "/selectUserInfo",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectUserInfo(Integer userId){

        ResponseData data = new ResponseData();

        Map<String,Object> userInfo = userService.selectUserInfo(userId);

        data.setResults(userInfo);

        // 返回数据
        return data;
    }

    /**
     * 根据id删除用户及相关信息
     * @return
     */
    @ApiOperation(value = "删除用户",notes="删除用户")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userId",dataType="int",required=false,value="用户id",defaultValue = "1"),
    })
    @RequestMapping(value = "/deleteUserInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData deleteUserInfo(Integer userId){

        ResponseData data = new ResponseData();

        Integer status = userService.deleteUserInfo(userId);

        switch (status) {
            case 0:{
                data.setCodeEnum(CodeEnum.SUCCESS);
            }
            break;
            case 1:{ // 用户不存在
                data.setCodeEnum(CodeEnum.CODE_10003);
            }
            break;
            case 2:{ // 该用户已有已完成订单
                data.setCodeEnum(CodeEnum.CODE_10019);
            }
            break;
        }

        data.setResults(status);

        // 返回数据
        return data;
    }

    /**
     * 查询用户优惠券列表
     * @return
     */
    @ApiOperation(value = "查询用户优惠券列表",notes="查询用户优惠券列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userId",dataType="int",required=false,value="用户Id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="serviceId",dataType="string",required=false,value="服务id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="orderCost",dataType="double",required=false,value="订单金额",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="subclinicId",dataType="int",required=false,value="分店id",defaultValue = "1"),
    })
    @RequestMapping(value = "/selectUserCouponList",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectUserCouponList(Integer userId,double orderCost,String serviceId,Integer subclinicId){

        ResponseData data = new ResponseData();

        Map<String,Object> params = new HashMap<>();
        params.put("userId", userId);
        params.put("orderCost", orderCost);
        params.put("serviceId", serviceId);
        params.put("subclinicId", subclinicId);

        data.setResults(commonService.selectUserDiscountList(params));

        // 返回数据
        return data;
    }
    /**
     * 查询用户次卡列表
     * @return
     */
    @ApiOperation(value = "查询用户次卡列表",notes="查询用户次卡列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userId",dataType="string",required=false,value="用户Id",defaultValue = "1"),
    })
    @RequestMapping(value = "/selectUserCardList",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectUserCardList(Integer userId){

        ResponseData data = new ResponseData();

        Map<String,Object> params = new HashMap<>();
        params.put("userId", userId);

        data.setResults(commonService.selectUserCardList(params));

        // 返回数据
        return data;
    }
    /**
     * 申请退款
     * @return
     */
    @ApiOperation(value = "申请退款",notes="申请退款")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="subclinicId",dataType="int",required=false,value="分店id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="applyUserId",dataType="int",required=false,value="用户id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="applyUserName",dataType="string",required=false,value="姓名",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="applyUserPhone",dataType="string",required=false,value="手机号",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="applyReason",dataType="string",required=false,value="备注",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="backAccount",dataType="double",required=false,value="金额",defaultValue = "1"),
    })
    @RequestMapping(value = "/saveBackCardInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData saveBackCardInfo(HttpServletRequest request, TBackcardInfo backcardInfo){

        ResponseData data = new ResponseData();

        SysUserInfo userInfo = (SysUserInfo) request.getSession().getAttribute(HttpUtils.CURRENT_USER_4_POJO);

        backcardInfo.setUserId(userInfo.getUserId());

        Integer count = commonService.saveBackCardInfo(backcardInfo);

        if(count == 0 ){
            data.setCodeEnum(CodeEnum.CODE_60016);
            return data;
        }

        data.setResults(count);

        // 返回数据
        return data;
    }
    /**
     * 退款查询退款列表
     * @return
     */
    @ApiOperation(value = "退款查询退款列表",notes="退款查询退款列表")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="subclinicId",dataType="int",required=false,value="当前门店id",defaultValue = "1"),
    })
    @RequestMapping(value = "/selectBackCardInfoList",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectBackCardInfoList(HttpServletRequest request){

        ResponseData data = new ResponseData();

        Map<String,Object> params = HttpUtils.getAllReqParams(request);

        data.setResults(commonService.selectBackCardInfoList(params));

        // 返回数据
        return data;
    }
    /**
     * 退款详情
     * @return
     */
    @ApiOperation(value = "退款详情",notes="退款详情")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="applyUserId",dataType="int",required=false,value="用户id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="subclinicId",dataType="int",required=false,value="当前门店id",defaultValue = "1"),
    })
    @RequestMapping(value = "/selectBackCardInfo",method = RequestMethod.GET)
    @ResponseBody
    public ResponseData selectBackCardInfo(TBackcardInfo backcardInfo){

        ResponseData data = new ResponseData();

        Map<String,Object> retMap = commonService.selectBackCardInfo(backcardInfo);

        if( retMap == null ){
            data.setCodeEnum(CodeEnum.CODE_10010);
            return data;
        }
        data.setResults(retMap);
        // 返回数据
        return data;
    }
    /**
     * 审核退款
     * @return
     */
    @ApiOperation(value = "审核退款",notes="审核退款")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="backcardId",dataType="int",required=false,value="退款id",defaultValue = "1"),
    })
    @RequestMapping(value = "/updateBackCardInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData updateBackCardInfo(HttpServletRequest request){

        ResponseData data = new ResponseData();

        Map<String,Object> params = HttpUtils.getAllReqParams(request);

        Integer result = commonService.updateBackCardInfo(params);

        if(result == 0){
            data.setCodeEnum(CodeEnum.CODE_60017);
        } else {
            data.setCodeEnum(CodeEnum.CODE_60027);
        }
        // 返回数据
        return data;
    }
    /**
     * 添加用户
     * @return
     */
    @ApiOperation(value = "添加用户",notes="添加用户")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userName",dataType="int",required=false,value="用户姓名",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userPhone",dataType="int",required=false,value="用户手机",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userAddress",dataType="string",required=false,value="地址",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userBirthday",dataType="string",required=false,value="生日",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="subclinicId",dataType="int",required=false,value="分店",defaultValue = "1"),
    })
    @RequestMapping(value = "/saveUserInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData saveUserInfo(HttpServletRequest request,TUserInfo userInfo){

        SysUserInfo sysUserInfo = (SysUserInfo) request.getSession().getAttribute(HttpUtils.CURRENT_USER_4_POJO);

        ResponseData data = new ResponseData();

        userInfo.setSubclinicId(sysUserInfo.getSubclinicId());

        Integer vipId = commonService.saveUserInfo(userInfo);
        if (vipId == 0) {
            data.setCodeEnum(CodeEnum.CODE_10008);
            return data;
        }

        data.setResults(vipId);

        // 返回数据
        return data;
    }
    /**
     * 修改用户
     * @return
     */
    @ApiOperation(value = "修改用户",notes="修改用户")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userId",dataType="int",required=false,value="用户id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userName",dataType="string",required=false,value="用户姓名",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userImg",dataType="string",required=false,value="用户姓名",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userCode",dataType="string",required=false,value="用户手机",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userPhone",dataType="string",required=false,value="用户手机",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userPhones",dataType="string",required=false,value="用户手机",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userPhoness",dataType="string",required=false,value="用户手机",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userAddress",dataType="string",required=false,value="地址",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userBirthday",dataType="string",required=false,value="生日",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="subclinicId",dataType="int",required=false,value="分店",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userAccount",dataType="double",required=false,value="余额",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userFrom",dataType="int",required=false,value="来源",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="userGender",dataType="int",required=false,value="用户性别:0:男;1:女",defaultValue = "1"),
    })
    @RequestMapping(value = "/updateUserInfo",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData updateUserInfo(TUserInfo userInfo,String userCode){

        ResponseData data = new ResponseData();

        if(ObjUtils.isNotEmpty(userCode)){
            userInfo.setWidth(userCode);
        }

        Integer count = commonService.updateUserInfo(userInfo);

        switch (count) {
            case 0: {
                data.setCodeEnum(CodeEnum.CODE_10005);
            }
            break;
            case -1: {
                data.setCodeEnum(CodeEnum.CODE_10001);
            }
            break;
            case -2: {
                data.setCodeEnum(CodeEnum.CODE_10015);
            }
            break;
            case -3: {
                data.setCodeEnum(CodeEnum.CODE_10008);
            }
            break;
            case -4: {
                data.setCodeEnum(CodeEnum.CODE_10006);
            }
            break;
        }

        if(count == 0){
            data.setCodeEnum(CodeEnum.CODE_10005);
            return data;
        }
        if(count == -1){
            data.setCodeEnum(CodeEnum.CODE_10001);
            return data;
        }
        if(count == -2){
            data.setCodeEnum(CodeEnum.CODE_10015);
            return data;
        }
        // 返回数据
        return data;
    }
    /**
     * 绑定2-3联系人发送验证码
     * @return
     */
    @ApiOperation(value = " 绑定2-3联系人发送验证码",notes="绑定2-3联系人发送验证码")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userId",dataType="int",required=false,value="用户id",defaultValue = "1"),
    })
    @RequestMapping(value = "/updateUserSendCode",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData updateUserSendCode(Integer userId,String userPhones,String userPhoness){

        ResponseData data = new ResponseData();

        String userPhone = null;
        if(ObjUtils.isNotEmpty(userPhones)){
            userPhone = userPhones;
        }

        if(ObjUtils.isNotEmpty(userPhoness)){
            userPhone = userPhoness;
        }
        TUserInfo user = commonService.updateUserSendCode(userId, userPhone);

        if(ObjUtils.isEmpty(user)){
            data.setCodeEnum(CodeEnum.CODE_10016);
            return data;
        }

        // 返回数据
        return data;
    }


    /**
     * 自定义充值
     * @return
     */
    @ApiOperation(value = "自定义充值",notes="自定义充值")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query",name="userId",dataType="int",required=false,value="充值用户id",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="rechargeAccount",dataType="double",required=false,value="充值金额",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="rechargeDesc",dataType="string",required=false,value="充值备注",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="payWay",dataType="int",required=false,value="付款方式",defaultValue = "1"),
            @ApiImplicitParam(paramType="query",name="deduction",dataType="int",required=false,value="是否是扣款，1：是扣款",defaultValue = "0"),
    })
    @RequestMapping(value = "/customRecharge",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData customRecharge(HttpServletRequest request, Integer userId, BigDecimal rechargeAccount, String rechargeDesc, Integer payWay, Integer deduction){

        ResponseData data = new ResponseData();

        CodeEnum codeEnum = ObjUtils.validateParams(new Object[]{userId,rechargeAccount,payWay});
        if(ObjUtils.isNotEmpty(codeEnum)){
            data.setCodeEnum(CodeEnum.CODE_90001);
            return data;
        }

        if (deduction == null) deduction = 0;
        if (deduction != 1 && rechargeAccount.doubleValue() <= 0) {
            data.setCodeEnum(CodeEnum.CODE_10018);
            return data;
        }

        if (ObjUtils.isEmpty(rechargeDesc)) {
            if (deduction == 1) {
                rechargeDesc = "对账扣款";
            } else {
                rechargeDesc = "余额充值";
            }
        }

        SysUserInfo loginSysUser = (SysUserInfo) request.getSession().getAttribute(HttpUtils.CURRENT_USER_4_POJO);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("userId", userId);
        params.put("rechargeDesc", rechargeDesc);
        params.put("payWay", payWay);
        params.put("rechargeAccount", rechargeAccount);

        Integer res = userService.saveUserAccount(loginSysUser, params);

        if(res < 0){
            if (res == -10) {
                data.setCodeEnum(CodeEnum.CODE_10020);
                return data;
            }
            data.setCodeEnum(CodeEnum.CODE_10017);
            return data;
        }

        // 返回数据
        return data;
    }
}
